<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>设备看板</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="title">
      <span class="company">{{comapnyName}}</span>
      <div class="btns">
        <el-button-group>
          <el-button v-if="totalRow>rowNum" :disabled="hasScrolling||currentRowIndex===0" size="small" icon="el-icon-arrow-left"
            title="上一页" @click="handlePageBtn('pre')"></el-button>
          <search-btn ref="searchBtn" :machine-search="search" :machine-list="machineList" :has-radius="totalRow<=rowNum"
            @search-data="searchMachingData"></search-btn>
          <el-button v-if="totalRow>rowNum" :disabled="hasScrolling||currentRowIndex===totalRow-rowNum" size="small"
            icon="el-icon-arrow-right" title="下一页" @click="handlePageBtn('next')"></el-button>
        </el-button-group>
        <el-button size="small" @click="toBack">回到首页</el-button>
      </div>
    </div>
    <div class="machine-board-content">
      <template v-for="(machineList,rowIndex) in pageMachineList">
        <div :key="`machineRow_${rowIndex}`" :class="{'is-last-line':(rowIndex+1)%rowNum===0}" :style="{height:`calc(${100/rowNum}% - 3px)`}">
          <template v-for="(machine,index) in machineList">
            <machine-item :machine="machine" :is-show="getHasShow(rowIndex)" :chart-start-date="showDateList[showStartDateIndex]"
              :key="`machine_${index}`"></machine-item>
          </template>
        </div>
      </template>
    </div>
  </div>
</body>

<script src="https://upload.shinehao.com.cn/20190223085008echarts.min.4.2.1-rc.1.js"></script>
<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "./css/searchBtn.css",
    "./css/machineItem.css"
  ], [
    "/vueSystem/models/baseModel.js"
  ]);
</script>
<script src="./models/searchModel.js"></script>
<script src="./models/machineInfo.js"></script>
<script src="./searchBtn.js"></script>
<script src="./machineItem.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    watch: {
      currentRowIndex: function (newVal, oldVal) {
        var $content = $(this.$el).find('.machine-board-content');
        var scrollTop = $content.scrollTop();
        var top = $content.find(`>div:eq(${newVal})`).position().top;
        scrollTop += top;

        if (this.nonAnimate) {
          this.nonAnimate = false;
          $content.scrollTop(scrollTop);
          return;
        }

        var self = this;
        this.hasScrolling = true;
        $content.animate({
          scrollTop: scrollTop
        }, 1000, function () {
          self.hasScrolling = false;
          if (newVal === self.totalRow - self.rowNum) {
            self.currentRowIndex = 0;
            self.nonAnimate = true;
          }
        });
      }
    },
    data: function () {
      return {
        loading: false,
        basePath: SysUtil.getBasePath(),
        comapnyName: '',
        machineList: [],
        searchMachineList: [],
        pageMachineList: [],
        rowNum: 2,
        colNum: 3,
        currentRowIndex: 0,
        hasScrolling: false,
        showDateList: this.getShowDateList(),
        showStartDateIndex: 0,
        totalRow: 0,
        scrollTimeout: null,
        nonAnimate: false,
        search: null
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setComapnyName(),
        this.setMachineList()
      ]).then(function (res) {
        self.refreshMachineInfo().then(function () {
          self.toPageMachineList();
          self.loading = false;

          self.boardRuning();
        });
      });
    },
    methods: {
      getShowDateList: function () {
        var showDateList = [];
        var dateMoment = moment().subtract(29, 'day');
        var maxMoment = moment().subtract(9, 'day');
        while (maxMoment.isAfter(dateMoment)) {
          showDateList.push(dateMoment.format('YYYY-MM-DD'));
          dateMoment.add(1, 'day');
        }
        return showDateList;
      },

      setComapnyName: function () {
        var self = this;
        return ajaxRequest('user/getUserName').then(function (user) {
          self.comapnyName = user.company;
          return user;
        }).catch(function () {
          return null;
        });
      },

      setMachineList: function () {
        var self = this;
        return ajaxRequest('equipment/getEquipmentBoard').then(function (machineList) {
          machineList = _.map(machineList, function (machine) {
            machine = new MachineInfo(machine);
            return machine;
          });
          self.machineList = machineList;
          self.searchMachingData();
          return machineList;
        }).catch(function () {
          return null;
        });
      },

      refreshMachineInfo: function () {
        var self = this;
        var machineList = this.machineList;
        var equipmentNoList = _.map(machineList, 'equipmentNo');
        return ajaxRequest('equipment/getDynamicEquipmentBoardData', {
          equipmentNos: JSON.stringify(equipmentNoList)
        }, true, false).then(function (machineData) {
          if (machineData === null) {
            machineData = {};
          }
          for (var i = 0; i < machineList.length; i++) {
            var machine = machineList[i];
            var data = machineData[machine.equipmentNo];
            if (data !== undefined) {
              machine.refreshData(data);
            }
          }
          return machineList;
        }).catch(function () {
          return machineList;
        });
      },

      toPageMachineList: function () {
        var machineList = this.searchMachineList;
        var pageMachines = [];
        var colNum = this.colNum;
        var rowNum = this.rowNum;
        var totalRow = machineList.length / colNum;
        totalRow = _.round(totalRow, 1);
        totalRow = Math.ceil(totalRow);
        totalRow = totalRow < rowNum ? rowNum : totalRow;
        for (var i = 0; i < totalRow; i++) {
          pageMachines.push([]);
        }

        var lastRow = 0;
        for (var i = 0; i < machineList.length; i++) {
          var machine = machineList[i];
          var rowIndex = i / colNum;
          rowIndex = Math.floor(rowIndex);
          pageMachines[rowIndex].push(machine);
          if (i === machineList.length - 1) {
            lastRow = rowIndex;
          }
        }

        var lastMachine = pageMachines[lastRow];
        if (lastMachine.length > 0) {
          for (var i = lastMachine.length; i < colNum; i++) {
            lastMachine.push(null);
          }
        }

        if (totalRow > rowNum) {
          var num = totalRow % rowNum;
          if (num !== 0) {
            for (var i = 0; i < num; i++) {
              var array = [];
              for (var i = 0; i < colNum; i++) {
                array.push(null)
              }
              pageMachines.push(array);
            }
          }
          for (var i = 0; i < rowNum; i++) {
            pageMachines.push(pageMachines[i]);
          }
        }
        this.totalRow = pageMachines.length;
        this.pageMachineList = pageMachines;
      },

      getHasShow: function (rowIndex) {
        var rowNum = this.rowNum;
        var totalRow = this.totalRow;
        if (rowNum >= totalRow) {
          return true;
        }

        var currentRowIndex = this.currentRowIndex;
        if (rowIndex >= currentRowIndex && rowIndex <= currentRowIndex + rowNum - 1) {
          return true;
        }
        return false;
      },

      toBack: function () {
        var basePath = this.basePath;
        location.href = basePath + "/datav/index.html?autoLogin=autoLogin";
      },

      boardRuning: function () {
        this.scrollRuning();
        this.setMachineDataRuning();
        this.resetMachineInfoRuning();
        this.resetMachineListRuning();
      },

      scrollRuning: function () {
        var self = this;
        this.scrollTimeout = setTimeout(function () {
          self.toNextPage();
          self.scrollTimeout = null;
          self.scrollRuning();
        }, 10500);
      },

      toNextPage: function () {
        var currentRowIndex = this.currentRowIndex;
        var totalRow = this.totalRow;
        var rowNum = this.rowNum;
        if (totalRow <= rowNum) {
          return;
        }

        this.currentRowIndex = (currentRowIndex + this.rowNum) % totalRow;
      },

      setMachineDataRuning: function () {
        var self = this;
        setTimeout(function () {
          var showStartDateIndex = self.showStartDateIndex;
          var showDateList = self.showDateList;
          if (showDateList.length === 0) {
            self.showStartDateIndex = 0;
            return;
          }
          var index = (showStartDateIndex + 1) % showDateList.length;
          self.showStartDateIndex = index;
          self.setMachineDataRuning();
        }, 5000);
      },

      resetMachineInfoRuning: function () {
        var self = this;
        setTimeout(function () {
          self.refreshMachineInfo().then(function(){
            self.resetMachineInfoRuning();
          });
        }, 5000);
      },

      resetMachineListRuning: function () {
        var tomorrowMoment = moment().add(1, 'day').startOf('day').set({
          hour:1
        });
        var delayTime = tomorrowMoment.diff(moment());

        var self = this;
        setTimeout(function () {
          self.setMachineList().then(function () {
            self.refreshMachineInfo().then(function () {
              self.toPageMachineList();
              self.showDateList = self.getShowDateList();
              self.currentRowIndex = 0;
              self.resetMachineListRuning();
            });
          });
        }, delayTime);
      },

      searchMachingData: function (deptWorkshop) {
        if (deptWorkshop === undefined) {
          deptWorkshop = this.$refs['searchBtn'].getSearchObject();
        }
        var machineList = this.machineList;
        if (deptWorkshop === null) {
          machineList = _.clone(machineList);
        } else {
          machineList = _.filter(machineList, deptWorkshop);
        }
        this.searchMachineList = machineList;
        if (this.currentRowIndex !== 0) {
          this.currentRowIndex = 0;
          this.nonAnimate = true;
        }
      },

      handlePageBtn: function (direction) {
        var currentRowIndex = this.currentRowIndex;
        var totalRow = this.totalRow;
        var rowNum = this.rowNum;
        if (totalRow <= rowNum) {
          return;
        }

        var currentRowIndex;
        if (direction === 'next') {
          currentRowIndex = (currentRowIndex + this.rowNum) % totalRow;
        } else {
          currentRowIndex = (currentRowIndex - this.rowNum) % totalRow;
        }
        this.currentRowIndex = currentRowIndex;

        var scrollTimeout = this.scrollTimeout;
        if (scrollTimeout !== null) {
          clearTimeout(scrollTimeout);
        }
        this.scrollRuning();
      }
    },
    components: {
      MachineItem: MachineItem,
      SearchBtn: SearchBtn
    }
  });
</script>
<style>
  #app {
    background: #0E2A43;
  }

  .title {
    height: 43px;
    text-align: center;
    background-size: 176px 40px;
    background-repeat: no-repeat;
    background-color: #000;
    position: relative;
  }

  .title .btns {
    position: absolute;
    right: 10px;
    top: 0;
    padding-top: 5px;
  }

  .title .company {
    color: #ffffff;
    font-size: 20px;
    line-height: 43px;
  }

  .machine-board-content {
    height: calc(100% - 53px);
    overflow: hidden;
    margin: 5px;
    position: relative;
  }

  .machine-board-content>div {
    margin-bottom: 6px;
    display: flex;
  }

  .machine-board-content>div.is-last-line {
    margin-bottom: 0;
  }

  .machine-board-content .machine-item {
    flex: 1;
    margin-right: 5px;
  }

  .machine-board-content .machine-item:last-child {
    margin-right: 0;
  }
</style>

</html>